package com.duomn.mybatis.plugins.parse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.duomn.mybatis.plugins.IShardingConfig;
import com.duomn.mybatis.plugins.ISqlParser;
import com.duomn.mybatis.plugins.config.ShardingConfigImpl;
import com.duomn.mybatis.plugins.model.ExecuteMode;
import com.duomn.mybatis.plugins.model.ParsedStatement;

public class SQLParserImpl implements ISqlParser {
	
	/** prepared sql */
	private String sql;
	
	/** parameter */
	private List<Object> params;
	
	private IShardingConfig shardingConfig = new ShardingConfigImpl();
	
	public SQLParserImpl(String sql, List<Object> params) {
		this.sql = sql;
		this.params = params;
	}

	@Override
	public ParsedStatement getParsedStatement() {
		ParsedStatement parsedSt = new ParsedStatement();
		
		// 2.提取使用到的表名，子查询有多个表名
		List<String> tableName = null;
		
//		if (!shardingConfig.supplyShading(tableName)) 
//			return parsedSt;
		
		
		// 3.提取使用到的条件名称
		
		
		
		
		// 4.提取使用到的条件对应的参数
		
		
		if (shardingConfig.supplyShading("sample")) {
			String[] tableNames = shardingConfig.getShadingTables("sample", null);
			if (sql.startsWith("select")) {
				parsedSt.setMode(ExecuteMode.EXE_ALL);
				String[] sqls = replaceSql(sql, "sample", tableNames);
				parsedSt.setSqls(Arrays.asList(sqls));
			} else if (sql.startsWith("insert")) {
				parsedSt.setMode(ExecuteMode.EXE_ONLY);
				String rSql = sql.replaceAll("([ \t\n\r\f,]*)" + "sample" + "([ \t\n\r\f,]*)", "$1" + tableNames[tableNames.length - 1] + "$2");
				List<String> sqls = new ArrayList<String>();
				sqls.add(rSql);
				parsedSt.setSqls(sqls);
			} else if (sql.startsWith("delete")) {
				parsedSt.setMode(ExecuteMode.EXE_ALL);
				String[] sqls = replaceSql(sql, "sample", tableNames);
				parsedSt.setSqls(Arrays.asList(sqls));
			} else if (sql.startsWith("update")) {
				parsedSt.setMode(ExecuteMode.EXE_ALL);
				String[] sqls = replaceSql(sql, "sample", tableNames);
				parsedSt.setSqls(Arrays.asList(sqls));
			}
		}
		return parsedSt;
	}
	
	private String[] replaceSql(String sql, String tableName, String[] tableNames) {
		String[] sqls = new String[tableNames.length];
		for (int i = 0; i < tableNames.length; i++) {
			sqls[i] = sql.replaceAll("([ \t\n\r\f,]*)" + tableName + "([ \t\n\r\f,]*)", "$1" + tableNames[i] + "$2");
		}
		return sqls;
		
	}
	
	public static void main(String[] args) {
		String sql = "select * from sample, orders where a = b";
		String tableName = "sample";
		String[] tableNames = {"sample_1", "sample_2"};
		
		SQLParserImpl sp = new SQLParserImpl(sql, null);
		String[] sqls = sp.replaceSql(sql, tableName, tableNames);
		System.out.println(JSON.toJSONString(sqls));
	}
	

}
